
import { _decorator, Component, Label, NodePool, Scheduler, Vec2, instantiate, Prefab, Node, Vec3, find, director, AudioSource, UITransform, tween } from 'cc';
import lyric from '../Data/Lyric';
import lyric2 from '../Data/Lyric2';
import lyric3 from '../Data/Lyric3';
import Fish from '../Data/FishData';
import { AudioMng } from './AudioMng';
import { Card } from './Card';
import { CountDown } from './CountDown';
const { ccclass, property } = _decorator;

@ccclass('Game')
export class Game extends Component {
    
    @property(Prefab)
    Card: Prefab = null;

    @property(Prefab)
    CardAreaPrefab: Prefab = null;

    @property(Node)
    QuestionArea: Node = null;

    @property(Node)
    QuestionMask: Node = null;

    @property(Node)
    Info: Node = null;

    @property(Node)
    AnswerArea: Node = null;

    @property(Node)
    AnswerCardArea: Node = null;
    
    @property(Node)
    ResultWin: Node = null;

    @property(Prefab)
    Fish1: Prefab = null;

    @property(Prefab)
    Fish2: Prefab = null;

    @property(Prefab)
    Fish3: Prefab = null;

    @property(Prefab)
    Fish4: Prefab = null;

    @property(Prefab)
    Fish5: Prefab = null;

    @property(Prefab)
    Fish6: Prefab = null;

    @property(Prefab)
    Fish7: Prefab = null;
    
    @property(Prefab)
    Fish8: Prefab = null;

    @property(Prefab)
    Fish9: Prefab = null;

    @property(Prefab)
    Fish10: Prefab = null;

    CardArea: Node = null;
    CardSortArea: Node = null;
    level: number = 1;
    stage: number = 0;
    choiceArr = [];
    answerArr = [];
    _cardPool: NodePool;
    _original: string = '';
    _timer = 7;
    _fish = null;
    FishNode = null;
    type = 1;
    lyric = null;
    btnDisabled = true;
    private column: number = 7;
    private cardWidth: number = 70;
    private cardHeight: number = 70;

    start() {
        if(this.type == 1) {
            this.lyric = this.randomSort(lyric);
        } else if(this.type == 2) {
            this.lyric = this.randomSort(lyric2);
        } else if(this.type == 3) {
            this.lyric = this.randomSort(lyric3);
        }
        this.startGame();
    }

    startGame() {
        this.btnDisabled = true;
        this.Info.getChildByName('Title').getComponent(Label).string = `关卡:${this.stage + 1}`;
        this.ResultWin.active = false;
        this.QuestionMask.active = true;
        this._original = this.lyric[this.stage];
        this.level = Math.floor(this.stage / 4);
        this._fish = Fish[this.level].name;
        this.choiceArr = this.randomSort(this._original.split(''));
        this.CardArea = instantiate(this.CardAreaPrefab);
        const chooseCard = find('/Canvas/CardWrap');
        let column = 0;
        chooseCard.addChild(this.CardArea);
        this.CardSortArea = this.CardArea.getChildByName('CardSortArea');
        this.setTextBoard(this._original);
        this.clear();
        const countTimer = this._timer - this.level > 3 ? this._timer - this.level : 3;
        const countDownPop = this.QuestionMask.getComponent(CountDown);

        countDownPop.setCountDown(countTimer, () =>{
            this.QuestionMask.active = false;
            this.btnDisabled = false;
            countDownPop.clearTimeout();
        });

        this.QuestionMask.getChildByName('QuickStart').getChildByName('QuickBtn').on('click', () => {
            this.QuestionMask.active = false;
            this.btnDisabled = false;
            countDownPop.clearTimeout();
        }, this);

        this.choiceArr.map((item, index) => {
            if(index != 0 && index % this.column == 0) {
                column++;
            }
            this.createCard(new Vec2((index % this.column) * this.cardWidth, -(column * this.cardHeight)), item, index);
            
        })
    }

    setTextBoard(text: string) {
        this.QuestionMask.getChildByName('QuestionBoard').getChildByName('QuestionContent').getChildByName('Content').getComponent(Label).string = text;
    }

    createCard(pos: Vec2, text: string, index: number) {
        const iCard = instantiate(this.Card);
        const cardComp = iCard.getComponent(Card);
        cardComp.init(new Vec3(pos.x, pos.y), text, index);
        this.CardSortArea.addChild(iCard);

        iCard.on(Node.EventType.TOUCH_END, (e) => {
            const content = cardComp.getContent();
            let currIndex = -1;
            e.target.active = false;
            if(this.answerArr.length > 0) {
                let hasContent = false;
                for(let i = 0;i < this.answerArr.length; i++) {
                    if(this.answerArr[i] == '') {
                        currIndex = i;
                        this.answerArr.splice(i, 1, content);
                        hasContent = true;
                        break;
                    }
                }
                if(!hasContent) {
                    this.answerArr.push(content);
                }
            } else {
                this.answerArr.push(content);
            }
            this.createAnswerCard(e.target, pos, currIndex)
        }, this)
    }

    createAnswerCard(choicecard: Node, posi: Vec2, ind: number = -1) {
        const iCard = instantiate(this.Card);
        const cardComp = iCard.getComponent(Card);
        const index = ind == -1 ? this.answerArr.length - 1 : ind;
        const text = this.answerArr[index];
        let column = 0;
        for(let j = 0; j < this.answerArr.length; j++) {
            if(j != 0 && j % this.column == 0) {
                column++;
            }
            if(j == index) {
                break;
            }
        }
        const pos = new Vec2((index % this.column) * this.cardWidth, -(column * this.cardHeight));
        cardComp.init(new Vec3(pos.x, pos.y), text, index);
        this.AnswerCardArea.addChild(iCard);
        iCard.on(Node.EventType.TOUCH_END, (e) => {
            const i = cardComp.getIndex();
            choicecard.active = true;
            this.answerArr.splice(i, 1, '');
            e.target.destroy();
        }, this)
    }

    sortAnswerCard() {
        const allChildren = this.AnswerArea.children;
        const childrenArr = [];
        for(let i = 0; i < allChildren.length; i++) {
            if(allChildren[i].name == 'Card') {
                childrenArr.push(allChildren[i]);
            }
        }
        let column = 0;
        childrenArr.map((item, index) => {
            if(index != 0 && index % this.column == 0) {
                column++;
            }
            item.setPosition((index % this.column) * this.cardWidth, -(column * this.cardHeight));
        })
    }

    onLoad() {
        this._cardPool = new NodePool();
    }

    update() {
        this.sortAnswerCard();
    }

    clear() {
        const allChildren = this.AnswerCardArea.children;
        const allCardChildren = this.CardSortArea.children;
        this.answerArr = [];
        for(let i = 0; i < allChildren.length; i++) {
            if(allChildren[i].name !== 'AnswerBg') {
                allChildren[i].destroy();
            }
        }
        for(let i = 0; i < allCardChildren.length; i++) {
            if(allCardChildren[i].name == 'Card') {
                allCardChildren[i].active = true;
            }
        }
    }

    submit() {
        if(this.btnDisabled) {
            return;
        }
        const result = this.answerArr.join('');
        this.ResultWin.active = true;
        this.FishNode = instantiate(this[`Fish${this.level + 1}`]);
        const FishBox = this.ResultWin.getChildByName('Fish');
        FishBox.removeAllChildren();
        FishBox.addChild(this.FishNode);
        FishBox.active = true;
        if(result == this._original) {
            find("/Game/Audio").getComponent(AudioMng).playWin();
            this.ResultWin.getChildByName('Default').active = false;
            this.ResultWin.getChildByName('Success').active = true;
            this.ResultWin.getChildByName('Title').getComponent(Label).string = '哎呦，还不错哦';
            this.stage++;
            if(this.stage >= this.lyric.length || this.stage >= 100) {
                this.stage = 0;
            }
        } else {
            find("/Game/Audio").getComponent(AudioMng).playDefeat();
            this.ResultWin.getChildByName('Default').active = true;
            this.ResultWin.getChildByName('Success').active = false;
            this.ResultWin.getChildByName('Title').getComponent(Label).string = this._fish;
        }
    }

    restart() {
        this.CardArea.active = false;
        this.CardArea.destroy();
        this.startGame();
    }

    randomSort(array) {
        const arr = array;
        for(let i = 0;i < arr.length; i++) {
            const r = Math.random() * (arr.length - 1);
            const j = parseInt(`${r}`);
            const curr = arr[i];
            arr[i] = arr[j];
            arr[j] = curr;
        }
        return arr;
    }

    back() {
        director.loadScene("Menu");
    }
}
